import React, { Component } from 'react'
import { connect } from 'react-redux'
import { validForm as validFormDuck } from 'ducks'
import { Table, Form, Message } from 'semantic-ui-react'
import Styled from 'styled-components'
import { BasicButton, PrimaryButton } from 'components/Button'
import { ValidInput } from 'components/validForm'

const SectionRow = Styled.div`
  margin-bottom: 1em;
`
class DatasetConfig extends Component {
  static propTypes = {}

  componentDidMount = () => {
    const {
      actionInitField, name, required, fieldInitValue, nullable, initValue,
    } = this.props
    actionInitField({
      name,
      state: nullable ? 'success' : 'init',
      required,
      value: initValue !== undefined ? initValue : fieldInitValue,
    })
  }

  render() {
    const {
      header,
      description,
      actionInitField,
      field,
      submit,
      red,
      message,
      ...others
    } = this.props
    return (
      <Table.Row>
        <Table.Cell width="4" verticalAlign="top">
          <font color={red ? '#db2828' : '#000000'}>{header}</font>
        </Table.Cell>
        <Table.Cell>
          {message && (
            <SectionRow>
              <Message error header={message.header} list={message.list} />
            </SectionRow>
          )}
          <SectionRow>
            <font color={red ? '#db2828' : '#000000'}>{description}</font>
          </SectionRow>
          <SectionRow>
            <Form>
              {field && (
                <Form.Field inline>
                  <ValidInput {...others} />
                </Form.Field>
              )}
            </Form>
          </SectionRow>
          {submit && (
            <SectionRow>
              <BasicButton content="取消" />
              <PrimaryButton content="保存" primary />
            </SectionRow>
          )}
        </Table.Cell>
      </Table.Row>
    )
  }
}

const mapStateToProps = (state, ownProps) => ({
  field: validFormDuck.selectors.field(state, ownProps.name),
  fieldInitValue: validFormDuck.selectors.fieldInitValue(state, ownProps.name),
})

const mapDispatchToProps = {
  actionInitField: validFormDuck.creators.actionInitField,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(DatasetConfig)
